<template>
  <div class="home">
    <div class="title-container">
      <div class="search-content">
        <el-form :model="searchModel" :inline="true">
          <el-form-item>
            <el-input
              v-model="searchModel.userName"
              :disabled="detailsDisabled"
              placeholder="请输入数据源名称"
              prefix-icon="el-icon-search"
            />
          </el-form-item>
        </el-form>
        <div class="search-btn">
          <el-button
            type="primary"
            icon="el-icon-search"
            @click="searchClick"
            size="medium"
          >搜索
          </el-button>
        </div>
      </div>
    </div>

    <el-card>
      <div class="addAccount">
        <perButton label="新建" type="primary" icon="el-icon-plus" size="medium" perms="PT_USER_ADD"
                   @click="handlerAccount"></perButton>
        <el-button
          type="success"
          icon="el-icon-refresh"
          size="medium"
          @click="refresh"
        >刷新
        </el-button>
      </div>
      <el-table
        v-loading="loading"
        :data="tableData"
        row-key="id"
        border
        style="width: 100%;"
        class="elTable"
      >
        <el-table-column type="index" label="序号" width="50" align="center"/>
        <el-table-column prop="sourceCode" label="数据源编码" align="center"/>
        <el-table-column prop="sourceName" label="数据源名称" align="center"/>
        <el-table-column prop="vueCode" label="同步识别码" align="center"/>
        <el-table-column prop="ipAddress" label="同步IP地址" align="center"/>
        <el-table-column prop="ipPort" label="同步端口号" align="center"/>
        <el-table-column prop="createByName" label="创建人" align="center"/>
        <el-table-column label="创建时间" align="center" prop="createTime">
          <template slot-scope="scope">
            {{ scope.row.createTime }}
          </template>
        </el-table-column>
        <el-table-column prop="updateByName" label="更新人" align="center"/>
        <el-table-column label="更新时间" align="center" prop="createTime">
          <template slot-scope="scope">
            {{ scope.row.updateTime }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300" align="center">
          <template #default="{ row }">
            <perButton label="数据同步" type="primary" size="mini" perms="PT_USER_EDIT"
                       @click="handlerAsyncData(row)"></perButton>
            <perButton label="编辑" type="warning" size="mini" perms="PT_USER_EDIT"
                       @click="handlerEdit(row)"></perButton>
            <perButton label="删除" type="danger" size="mini" perms="PT_USER_DEL"
                       @click="handlerDelete(row)"></perButton>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        class="pagination"
        :total="count"
        :page.sync="pageIndex"
        :limit.sync="pageSize"
        @pagination="getAccountData"
      />
    </el-card>

    <!-- 新建 -->
    <yc-dialog ref="ycDialog" :dialogTitle="dialogTitle" :centerTitle="centerTitle">
      <template #content>
        <div class="dialog-content">
          <el-form
            ref="newAccountFormRef"
            :rules="newAccountModelRules"
            :model="newAccountModel"
            :disabled="detailsDisabled"
            label-width="100px"
          >
            <el-form-item label="数据源名称" prop="sourceName">
              <el-input v-model="newAccountModel.sourceName"/>
            </el-form-item>
            <el-form-item label="同步识别码" prop="vueCode">
              <el-input v-model="newAccountModel.vueCode"/>
            </el-form-item>
            <el-form-item label="同步IP地址" prop="ipAddress">
              <el-input v-model="newAccountModel.ipAddress"/>
            </el-form-item>
            <el-form-item label="同步端口号" prop="ipPort">
              <el-input v-model="newAccountModel.ipPort"/>
            </el-form-item>
          </el-form>
        </div>
      </template>
      <template #footer>
        <el-button type="primary" :loading="addOrUpdateLoading" @click="dialogSave">确定</el-button>
        <el-button @click="$refs.ycDialog.dialogVisible = false">取消</el-button>
      </template>
    </yc-dialog>

    <!-- 数据同步 -->
    <yc-dialog ref="asyncDialog" :dialogTitle="dialogTitle" :show-center="false" dialog-width="70%">
      <template #content>
        <div class="dialog-content">
          <el-button type="primary" size="medium" :loading="addOrUpdateLoading" @click="asyncDataSave">数据同步</el-button>
          <el-button type="success" icon="el-icon-refresh" size="medium" @click="refresh2()">刷新
          </el-button>
          <el-table
            :data="asyncData"
            border
            style="width: 100%;"
            class="elTable"
          >
            <el-table-column type="index" label="序号" width="50" align="center"/>
            <el-table-column prop="getCode" label="同步流水号" align="center"/>
            <el-table-column prop="sourceCode" label="数据源编码" align="center"/>
            <el-table-column prop="sourceName" label="数据源名称" align="center"/>
            <el-table-column prop="vueCode" label="同步识别码" align="center"/>
            <el-table-column prop="ipAddress" label="同步IP地址" align="center"/>
            <el-table-column prop="ipPort" label="同步端口号" align="center"/>
            <el-table-column label="同步状态" align="center" prop="createTime">
              <template slot-scope="scope">
                <el-tooltip v-if="scope.row.status=='fail'" class="item" effect="dark" :content="scope.row.failReason" placement="top">
                  <el-tag size="medium" :type="asyncStatus.find(item => item.type == scope.row.status).color">
                    {{ asyncStatus.find(item => item.type == scope.row.status).label }}
                  </el-tag>
                </el-tooltip>
                <el-tag v-else size="medium" :type="asyncStatus.find(item => item.type == scope.row.status).color">
                  {{ asyncStatus.find(item => item.type == scope.row.status).label }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </template>
      <template #footer>
        <el-button @click="$refs.asyncDialog.dialogVisible = false">取消</el-button>
      </template>
    </yc-dialog>


    <!-- 封装操作后弹框 -->
    <global-message
      v-if="isGlobalMessageShow"
      @receive="receive"
      :message="message"
    />
  </div>
</template>

<script>
  import ycDialog from "@/components/pageDialog"
  import perButton from "@/components/permissionButton"

  import {
    queryPage,
    insertByModel,
    updateByModel,
    deleteByModel,
    queryHisList,
    syncData
  } from "@/api/dataInsertConfig/IOTData"

  export default {
    components: {
      ycDialog,
      perButton
    },
    data() {
      return {
        isGlobalMessageShow: false,
        message: "",

        projectCode: "",
        tableData: [],
        count: 0,
        pageIndex: 1,
        pageSize: 10,
        loading: false,

        searchModel: {
          userName: "",
          status: null //正常/停用状态（全部）
        },

        newAccountModel: {
          sourceName: "",
          vueCode: "",
          ipAddress: "",
          ipPort: "",
          id: 0
        },
        newAccountModelRules: {
          sourceName: [{required: true, message: "请输入数据源名称", trigger: "blur"}],
          vueCode: [{required: true, message: "请输入同步识别码", trigger: "blur"}],
          ipAddress: [{required: true, message: "请输入同步IP地址", trigger: "blur"}],
          ipPort: [{required: true, message: "请输入同步端口号", trigger: "blur"}],
        },

        dialogTitle: "",
        centerTitle: "",

        asyncData: [],
        asyncStatus: [
          {type: 'ing', label: '同步中', color: ""},
          {type: 'over', label: '同步完成', color: "success"},
          {type: 'fail', label: '同步失败', color: "danger"},
        ],
        sourceCode: "",

        detailsDisabled: false,
        addOrUpdateLoading: false
      }
    },
    created() {
      this.projectCode = sessionStorage.getItem('projectCode')
      this.getAccountData()
    },
    methods: {
      /**
       * 获取表格方法
       */
      async getAccountData(tableInfo) {
        this.loading = true
        if (tableInfo) {
          const {userName, status} = tableInfo
          const {object} = await queryPage({
            projectCode: this.projectCode,
            pageIndex: this.pageIndex,
            pageSize: this.pageSize,
            userName,
            status
          })
          this.tableData = object.data
          this.count = object.count
          this.loading = false
        } else {
          const {object} = await queryPage({
            projectCode: this.projectCode,
            pageIndex: this.pageIndex,
            pageSize: this.pageSize
          })
          this.tableData = object.data
          this.count = object.count
          this.loading = false
        }
      },
      pagination(pageItem) {
        this.getAccountData(pageItem.page, pageItem.limit)
      },
      // 搜索按钮
      async searchClick() {
        this.getAccountData(this.searchModel)
      },

      /**
       * 删除按钮
       */
      async handlerDelete({id}) {
        this.$confirm("确定删除此数据吗", "删除操作", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "error",
          center: true
        }).then(async () => {
          const {message, status} = await deleteByModel({id})
          if (status == "200") {
            this.getAccountData()
            this.isGlobalMessageShow = true
            this.message = "success"
          } else {
            this.message = "error"
          }
        })
      },

      /**
       * 新建
       * */
      async handlerAccount() {
        this.dialogTitle = "添加"
        this.centerTitle = "添加"

        this.detailsDisabled = false
        this.addOrUpdateLoading = false
        this.$refs.ycDialog.dialogVisible = true

        Object.keys(this.newAccountModel).forEach((item) => {
          this.newAccountModel[item] = ""
        })
      },

      /**
       * 修改
       */
      async handlerEdit(row) {
        this.dialogTitle = "编辑"
        this.centerTitle = "编辑"

        this.newAccountModel.id = row.id
        this.newAccountModel.sourceName = row.sourceName
        this.newAccountModel.vueCode = row.vueCode
        this.newAccountModel.ipAddress = row.ipAddress
        this.newAccountModel.ipPort = row.ipPort

        this.addOrUpdateLoading = false
        this.detailsDisabled = false
        this.$refs.ycDialog.dialogVisible = true
      },

      dialogSave() {
        this.$refs.newAccountFormRef.validate(async (v) => {
          if (v) {
            this.addOrUpdateLoading = true
            if (this.detailsDisabled) {
              // 详情的确定
              this.$refs.ycDialog.dialogVisible = false
            } else if (this.newAccountModel.id) {
              const {id, sourceName, vueCode, ipAddress, ipPort} = this.newAccountModel
              const {message, status} = await updateByModel({
                projectCode: this.projectCode,
                id,
                sourceName, vueCode, ipAddress, ipPort
              })
              if (status == 200) {
                this.getAccountData()
                this.$refs.ycDialog.dialogVisible = false
                this.$message.success(message)
              }
            } else {
              const {sourceName, vueCode, ipAddress, ipPort} = this.newAccountModel
              const {message, status} = await insertByModel({
                projectCode: this.projectCode,
                sourceName, vueCode, ipAddress, ipPort
              })
              if (status == 200) {
                this.getAccountData()
                this.$refs.ycDialog.dialogVisible = false
                this.$message.success(message)
              }
            }
            this.addOrUpdateLoading = false
          }
        })
      },

      // 数据同步
      handlerAsyncData(row) {
        this.dialogTitle = "数据同步"
        this.sourceCode = row.sourceCode
        this.queryHisList()
        this.addOrUpdateLoading = false
        this.$refs.asyncDialog.dialogVisible = true
      },
      queryHisList() {
        queryHisList({
          sourceCode: this.sourceCode
        }).then(res => {
          this.asyncData = res.object
        })
      },
      refresh2() {
        this.queryHisList()
      },
      asyncDataSave() {
        this.$confirm('确定执行同步数据吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          syncData({
            sourceCode: this.sourceCode
          }).then(res => {
            if (res.status == 200) {
              this.queryHisList()
              this.$message.success(res.message)
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          });
        });
      },
      /**
       * 刷新
       */
      refresh() {
        this.searchModel = {
          userName: "",
          status: null
        }
        this.getAccountData()
      },

      /**
       * globalMessage的知道按钮的方法
       * */
      receive() {
        this.isGlobalMessageShow = false
      },
    }
  }
</script>

<style lang="scss" scoped>
  .status {
    display: inline-block;
    padding: 0 10px;
  }

  .title-container {
    display: flex;
    justify-content: flex-end;
    height: 60px;

    .search-content {
      margin-left: 20px;
      display: flex;
    }

    .addAccount {
      margin: 10px 20px;
    }
  }

  .pagination {
    display: flex;
    justify-content: flex-end;
  }


  .footer {
    height: 360px;
    display: flex;
    align-items: flex-end;
    // justify-content: st-end;
    padding: 5px 20px;
  }
</style>
